package com.ljy.iecasbasedemo

import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.lifecycleScope
import org.unicorn.android.base.BaseActivity
import org.unicorn.android.base.net.toJson
import org.unicorn.android.base.viewModels
import com.ljy.iecasbasedemo.databinding.ActivityMainBinding
import com.ljy.iecasbasedemo.viewModel.MainViewModel
import kotlinx.coroutines.flow.collect

class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {

    private val mainViewModel: MainViewModel by viewModels()

    override fun initView(bind: ActivityMainBinding) {
        bind.requestApi.setOnClickListener {
            mainViewModel.requestApi()
        }
        bind.requestApiFlow.setOnClickListener {
            mainViewModel.requestApi()
        }
    }

    override fun initData() {
        mainViewModel.testLiveData.distinctUntilChanged().observe(this) {
            binding.requestApi.text = it.toJson()
        }
        //错误示例
//        lifecycleScope.launchWhenStarted {
//            mainViewModel.testFlow.collect {
//                binding.requestApiFlow.text = it.toJson()
//            }
//            mainViewModel.testFlow1.collect {
//                binding.requestApiFlow1.text = it.toJson()
//            }
//        }

        //正确示例
        lifecycleScope.launchWhenStarted {
            mainViewModel.testFlow1.collect {
                binding.requestApiFlow1.text = it.toJson()
            }
        }
        lifecycleScope.launchWhenStarted {
            mainViewModel.testFlow1.collect {
                binding.requestApiFlow.text = it.toJson()
            }
        }
    }


}